package com.faker.core.generate.data.code.common.datetime;

import lombok.extern.slf4j.Slf4j;

import java.time.LocalDateTime;
import java.time.YearMonth;
import java.time.format.DateTimeFormatter;

/**
 * 日期时间生成生成器
 */
@Slf4j
public class DateTimeGenerator {

    public static void main(String[] args) {
        //生成今年的日期
        System.out.println(getDateTime(0, "yyyy-MM-dd HH:mm:ss"));
        //生成去年的日期
        System.out.println(getDateTime(1, "yyyy-MM-dd HH:mm:ss"));
        //生成前年的日期
        System.out.println(getDateTime(2, "yyyy-MM-dd HH:mm:ss"));
    }


    public static String getDateTime(int years, String format) {
        LocalDateTime now = LocalDateTime.now();
        int previousYear = now.minusYears(years).getYear();
        int month = randomBetween(1, 12);
        int day = randomBetween(1, YearMonth.of(previousYear, month).lengthOfMonth());
        int hour = randomBetween(0, 23);
        int minute = randomBetween(0, 59);
        int second = randomBetween(0, 59);
        LocalDateTime randomDateTime = LocalDateTime.of(previousYear, month, day, hour, minute, second);
        return randomDateTime.format(DateTimeFormatter.ofPattern(format));
    }

    public static int randomBetween(int minInclusive, int maxInclusive) {
        return (int) (Math.random() * (maxInclusive - minInclusive + 1)) + minInclusive;
    }
}